package com.yhb.channel.utils.encryptAndSign;

import lombok.Data;
import org.apache.commons.codec.binary.Base64;
import org.jetbrains.annotations.NotNull;

import java.io.*;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.Enumeration;

@Data
public class ChannelPrivateKeyUtils {

    private KeyStore keyStore; // 私钥存储
    private File privateKeyFile;
    private String privateKeyPassword;

    /**
     * 构造函数 创建keyStore
     */
    public ChannelPrivateKeyUtils(File privateKeyFile, @NotNull String privateKeyPassword)
            throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
        this.privateKeyFile = privateKeyFile;
        this.privateKeyPassword = privateKeyPassword;
        // 存入私钥
        keyStore = KeyStore.getInstance("PKCS12");
        InputStream inputStream = new FileInputStream(privateKeyFile);
        keyStore.load(inputStream, privateKeyPassword.toCharArray());
        inputStream.close();
    }

    /**
     * 获取私钥的别名
     */
    private String getPrivateKeyAlias() throws KeyStoreException {
        Enumeration<String> aliases = this.keyStore.aliases();
        String keyAlias = null;
        if (aliases.hasMoreElements()){
            // 只存了私钥一个
            keyAlias = aliases.nextElement();
        }
        return keyAlias;
    }

    /**
     * 获取私钥
     */
    public PrivateKey getPrivateKey() throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
        String keyAlias = this.getPrivateKeyAlias();
        return (PrivateKey) this.keyStore.getKey(keyAlias, this.privateKeyPassword.toCharArray());
    }

    /**
     * 获取私钥字符串
     */
    public String getPrivateKeyString() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
        return Base64.encodeBase64String(this.getPrivateKey().getEncoded());
    }
}
